import { openDB, closeDB, select, insert, update } from '@/assets/database'
import { suffix } from '@/assets/js/util.js'
import { renameAndMoveFile } from '@/assets/js/native.js'

const state = {
	task: []//下载任务
}

const getters = {
	get (state) {
		return state.task
	}
}

const actions = {
	create ({state, rootGetters}, {title, url, isAdult}) {
		if ( state.task.findIndex(t => t.url == url) > -1 ) {
			uni.showToast({
				title: '重复下载链接',
				icon: 'none'
			})
			return
		}
		const downloadTask = uni.downloadFile({
			url: url,
			success: async res => {
				if ( res.statusCode == 200 ) {
					try{
						const savePath = rootGetters['setting/GET_DOWNLOAD_PATH']
						const ret = savePath.startsWith('_doc/uniapp_save') ? await saveFile(res.tempFilePath) : await moveFile(res.tempFilePath, savePath, title)
						const taskIndex = state.task.findIndex(t => t.url == url)
						if ( taskIndex > -1 ) state.task.splice(taskIndex, 1)
						await openDB()
						await insert('download', {title: title, url: url, file_path: ret.savedFilePath, state: 1, is_adult: isAdult || 0})
						uni.showToast({
							title: title + ' 下载成功',
							icon: 'none'
						})
					}catch(e){
						uni.showToast({
							title: title + ' 下载失败，失败原因：' + JSON.stringify(e),
							icon: 'none'
						})
					}
					closeDB()
				}
			},
			fail: async err => {
				const message = title + ' 下载失败'
				const taskIndex = state.task.findIndex(t => t.url == url)
				if ( taskIndex > -1 ) state.task.splice(taskIndex, 1)
				try{
					await openDB()
					await insert('download', {title: title, url: url, file_path: '', state: 2, is_adult: isAdult || 0})
					uni.showToast({
						title: message,
						icon: 'none'
					})
				}catch(e){
					uni.showToast({
						title: message + '失败原因：' + JSON.stringify(e),
						icon: 'none'
					})
				}
				closeDB()
			}
		})
		state.task.push({
			title: title,
			url: url,
			progress: 0,
			instance: downloadTask
		})
		downloadTask.onProgressUpdate((res) => {
			const index = state.task.findIndex(t => t.url == url)
			if ( index > -1 ) state.task[index].progress = res.progress
		});
		uni.showToast({
			title: '已加入下载列表',
			icon: 'none'
		})
	},
	abort ({state}, url) {
		const index = state.task.findIndex(t => t.url == url)
		if ( index > -1 ) {
			state.task[index].instance.abort()
			state.task.splice(index, 1)
		}
	},
	abortAll ({state}) {
		for ( let i = 0; i < state.task.length; i++ ) state.task[i].instance.abort()
		state.task = []
	}
}


function saveFile (tempFilePath) {
	return new Promise((resolve, reject) => {
		uni.saveFile({
		  tempFilePath,
		  success: function (res) {
			resolve(res)
		  },
		  fail: (err) => {
		  	reject(err)
		  }
		});
	})
}

function moveFile (filePath, targetPath, newName) {
	return new Promise((resolve, reject) => {
		renameAndMoveFile({
			filePath,
			targetPath,
			newName,
			success: res => {
				resolve(res)
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

export default {
    namespaced: true,
    state,
    getters,
	actions
}